package openapi

import (
	"bufio"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"strconv"
	"strings"

	"github.com/getkin/kin-openapi/openapi3"
	"github.com/sirupsen/logrus"
)

func Load(uStr, username string) (*openapi3.T, error) {
	var f *os.File
	var err error
	var loader = openapi3.NewLoader()
	if uStr == "" {
		return nil, errors.New("没有指定加载地址/ID/文件名")
	} else if _, err = strconv.ParseInt(uStr, 10, 64); err == nil {
		req, err := http.NewRequest("GET", "https://rongapi.cn/api/definition/"+uStr+"/.json", nil)
		if err == nil {
			fmt.Println("请输入用户" + username + "的登陆密码：")
			reader := bufio.NewReader(os.Stdin)
			password, _ := reader.ReadString('\n')
			password = strings.TrimSpace(password)
			req.SetBasicAuth(username, password)
			var res *http.Response
			res, err = http.DefaultClient.Do(req)
			if err == nil {
				var bts []byte
				bts, err = ioutil.ReadAll(res.Body)
				defer res.Body.Close()
				if err == nil {
					var def *openapi3.T
					def, err := loader.LoadFromData(bts)
					if err == nil {
						if errS, ok := def.Extensions["Error"]; ok {
							switch ts := errS.(type) {
							case json.RawMessage:
								return nil, errors.New(string(ts))
							}
							return nil, fmt.Errorf("[%T]%v", errS, errS)
						}
					}
					return def, err
				}
			}
		}
	} else if f, err = os.Open(uStr); err == nil {
		logrus.Infoln("从本地文件加载yaml文件")
		var bts []byte
		bts, err = ioutil.ReadAll(f)
		if err == nil {
			return loader.LoadFromData(bts)
		}
	} else if u, err := url.Parse(uStr); err == nil {
		logrus.Infoln("从远程服务器下载yaml文件", u.String())
		return loader.LoadFromURI(u)
	}
	return nil, err
}
